<template>
  <div class="team-page-wrapper">
    <div class="team-page-container">
      <div class="team-search-section">
        <div class="search-header">
          <h1 class="page-title">寻找团队</h1>
          <p class="page-subtitle">寻找合适的项目，加入创新团队</p>
        </div>
        <div class="search-filter-container">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="24" :md="8" :lg="6">
              <a-input-search v-model:value="searchParams.name" placeholder="搜索团队名称或项目关键词" allow-clear
                @search="handleSearch" />
            </a-col>
            <a-col :xs="24" :sm="12" :md="8" :lg="6">
              <client-only><a-select v-model:value="searchParams.type" placeholder="比赛类型" style="width: 100%"
                  @change="handleTypeChange" allow-clear>
                  <a-select-option value="">全部比赛</a-select-option>
                  <a-select-option v-for="type in raceTypeList" :key="type.dictValue" :value="Number(type.dictValue)">
                    {{ type.dictLabel }}
                  </a-select-option>
                </a-select>
              </client-only>
            </a-col>
            <a-col :xs="24" :sm="12" :md="8" :lg="6">
              <client-only>
                <a-select v-model:value="searchParams.college" placeholder="按学院筛选" style="width: 100%"
                  @change="handleSearch" allow-clear>
                  <a-select-option value="">全部学院</a-select-option>
                  <a-select-option v-for="college in collegeList" :key="college.id" :value="college.id">
                    {{ college.name }}
                  </a-select-option>
                </a-select>
              </client-only>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="6" class="filter-buttons">
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                筛选
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 团队卡片展示区 -->
      <div class="team-cards-container">
        <a-row :gutter="[24, 24]">
          <a-col :span="24" v-if="loading">
            <div class="loading-container">
              <a-spin size="large" />
              <p>加载中...</p>
            </div>
          </a-col>
          <a-col :span="24" v-else-if="teamList.length === 0">
            <a-empty description="暂无符合条件的团队" />
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" v-for="(team, index) in teamList" :key="index">
            <div class="team-card" :class="{ 'team-card-urgent': isUrgent(team) }">
              <div class="team-card-header">
                <div class="team-card-title">
                  <h3>{{ team.name }}</h3>
                  <a-tag :color="getRaceTypeColor(team.type)">{{
                    getProjectType(team.type)
                  }}</a-tag>
                </div>
                <!-- <p class="team-college">{{ getCollegeName(team.id) }}</p> -->
                <p class="team-college">{{ team.scollege || "未知学院" }}</p>
              </div>

              <div class="team-card-body">
                <p class="team-description">
                  {{ team.description || "暂无简介" }}
                </p>

                <div class="team-members">
                  <div class="members-title">
                    <user-outlined />
                    <span>需求: {{ team.request || "暂无特殊要求" }}</span>
                  </div>
                  <div class="members-title">
                    <calendar-outlined />
                    <span>截止: {{ formatDate(team.end) }}</span>
                  </div>
                  <div class="members-title">
                    <team-outlined />
                    <span>招募:
                      <span class="member-count">{{ team.joinedCount || 0 }}/{{
                        team.number || 0
                      }}</span>人</span>
                  </div>
                </div>

                <div class="team-members">
                  <div class="members-title">
                    <crown-outlined />
                    <span>项目负责人: {{ team.leaderName }}</span>
                  </div>
                  <div class="teacher-info">
                    <book-outlined />
                    <span>指导老师: {{ team.t1Name
                    }}{{ team.t2Name ? "、" + team.t2Name : "" }}</span>
                  </div>
                </div>
              </div>

              <div class="team-card-footer">
                <a-button type="primary" class="join-button" shape="round" @click="applyToTeam(team)">
                  申请加入
                </a-button>
                <a-button type="link" @click="viewTeamDetail(team)">查看详情</a-button>
              </div>
              <div class="urgent-tag" v-if="isUrgent(team)">急需</div>
            </div>
          </a-col>
        </a-row>

        <!-- 分页 -->
        <div class="pagination-container" v-if="teamList.length > 0">
          <a-pagination v-model:current="pagination.current" :total="pagination.total" :pageSize="pagination.pageSize"
            @change="handlePageChange" show-size-changer :pageSizeOptions="['8', '16', '24', '32']"
            @showSizeChange="handleSizeChange" />
        </div>

        <!-- 申请加入模态框 -->
        <a-modal v-model:open="applyModalVisible" title="申请加入项目" @ok="submitApplication"
          :confirmLoading="submitLoading">
          <a-form :model="applicationForm" layout="vertical">
            <a-form-item label="个人简介" name="introduction">
              <a-textarea v-model:value="applicationForm.introduction" placeholder="请简要介绍自己的技能和经验" :rows="4" />
            </a-form-item>
            <a-form-item label="联系方式" name="contact">
              <a-input v-model:value="applicationForm.contact" placeholder="请留下您的联系方式" @blur="validateContact" />
              <div v-if="contactError" style="color: red; font-size: 12px;">
                {{ contactError }}
              </div>
            </a-form-item>
          </a-form>
        </a-modal>


        <!-- 详情信息 -->
        <a-modal v-model:visible="findOutVisible" title="查看团队详情" width="700px" :footer="null" class="custom-modal"
          :style="{ top: '2%' }">
          <div class="modal-content">
            <div class="info-item">
              <span class="label">团队名称：</span>
              <span class="value">{{ currentTeamDetail.name }}</span>
            </div>
            <div class="info-item">
              <span class="label">团队负责人：</span>
              <span class="value">{{ currentTeamDetail.leaderName }}</span>
            </div>
            <div class="info-item">
              <span class="label">负责人电话：</span>
              <span class="value">{{ currentTeamDetail.leaderInfo.phone }}</span>
            </div>
            <div class="info-item">
              <span class="label">负责人邮箱：</span>
              <span class="value">{{ currentTeamDetail.leaderInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">学号/工号：</span>
              <span class="value">{{ currentTeamDetail.leaderInfo.number }}</span>
            </div>
            <div class="info-item">
              <span class="label">比赛名称：</span>
              <span class="value">{{ currentTeamDetail.raceName }}</span>
            </div>
            <div class="info-item">
              <span class="label">比赛开始时间：</span>
              <span class="value">{{ currentTeamDetail.start }}</span>
            </div>
            <div class="info-item">
              <span class="label">比赛结束时间：</span>
              <span class="value">{{ currentTeamDetail.end }}</span>
            </div>
            <div class="info-item">
              <span class="label">所属学院：</span>
              <span class="value">{{ currentTeamDetail.t1College }}</span>
            </div>
            <div class="info-item">
              <span class="label">指导教师：</span>
              <span class="value">{{ currentTeamDetail.t1Name
              }}{{ currentTeamDetail.t2Name ? "、" + currentTeamDetail.t2Name : "" }}</span>
            </div>
            <div class="info-item">
              <span class="label">团队描述：</span>
              <span class="value">{{ currentTeamDetail.description }}</span>
            </div>
          </div>
        </a-modal>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { message } from "ant-design-vue";
import { useUserStore } from "@/store/user";
import {
  SearchOutlined,
  UserOutlined,
  CalendarOutlined,
  TeamOutlined,
  CrownOutlined,
  BookOutlined,
} from "@ant-design/icons-vue";
import { SYSYTM_TITLE } from "@/config";
import {
  getTeamList,
  getMajorList_api,
  getRaceType,
  getTeamMember,
  getTeamDetail,
  joinTeam,
} from "@/apis";
import { useRouter, useRoute } from "vue-router";

const user = useUserStore();

// 路由导航
const router = useRouter();
const route = useRoute();
const navigateTo = (path) => {
  router.push(path);
};

// 搜索参数
const searchParams = reactive({
  name: "",
  college: "",
  type: null,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 8,
  total: 0,
});

// 团队列表数据
const teamList = ref([]);
const loading = ref(false);

// 申请加入相关
const applyModalVisible = ref(false);
const submitLoading = ref(false);
const currentTeam = ref(null);
const applicationForm = reactive({
  introduction: "",
  contact: "",
});

const contactError = ref("");

const validateContact = () => {
  const value = applicationForm.contact;
  if (!value) {
    contactError.value = "联系方式不能为空";
  } else if (!/^\d{11}$/.test(value)) {
    contactError.value = "请输入有效的手机号码";
  } else {
    contactError.value = "";
  }
};

// 比赛类型数据
const raceTypeList = ref([
  { dictValue: 0, dictLabel: "大创立项" },
  { dictValue: 1, dictLabel: "学科竞赛" },
  { dictValue: 2, dictLabel: "第二课堂" },
]);

// 获取项目类型数据
const fetchRaceTypes = async () => {
  try {
    const res = await getRaceType();
    // console.log("比赛类型数据:", res);
    if (res && res.code === 200) {
      raceTypeList.value = res.rows || [];
      console.log("raceTypeList", raceTypeList.value);
    } else {
      console.warn("获取比赛类型失败:", res?.msg);
    }
  } catch (error) {
    console.error("获取比赛类型错误:", error);
  }
};


const getProjectType = (typeId) => {
  // console.log("raceTypeList", raceTypeList.value);
  // console.log("typeId", typeId);
  const type = raceTypeList.value.find(
    (item) => Number(item.dictValue) === typeId
  );
  console.log("type", type);
  return type ? type.dictLabel : "未知类型";
};



const getRaceTypeColor = (typeId) => {
  switch (typeId) {
    case 0:
      return "orange"; // 创新创业类比赛使用橙色
    case 1:
      return "blue"; // 蓝桥杯使用蓝色
    case 2:
      return "green"; // 第二课堂使用绿色
    default:
      return "gray"; // 默认灰色
  }
};

// 获取学院列表
const collegeList = ref([]);
const getCollegeList = async () => {
  const res = await getMajorList_api();
  collegeList.value = res.data.slice(0, 4);
  console.log("collegeList", collegeList.id);
  console.log("学院列表", collegeList.value);
};


// 获取学院名称
const getCollegeName = (collegeId) => {
  if (!collegeId) return "未知学院"; // 如果 collegeId 为 null、undefined 或 0
  const college = collegeList.value.find((item) => item.id === collegeId);
  return college ? college.name : "未知学院";
  console.log("学院列表", college);
};


// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "待定";
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 判断是否紧急项目（截止日期小于7天）
const isUrgent = (team) => {
  if (!team.end) return false;
  const endDate = new Date(team.end);
  const today = new Date();
  const diffTime = endDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays >= 0 && diffDays <= 7;
};

// 处理搜索请求
const handleSearch = () => {
  pagination.current = 1; // 重置到第一页
  fetchTeamList();
};

// 处理比赛类型变更
const handleTypeChange = (a) => {
  // console.log("a", a);
  handleSearch();
};

// 添加成员数量状态
const teamMembersCount = ref({});

// 获取团队成员数量
const fetchTeamMembersCount = async (teams) => {
  if (!teams || teams.length === 0) return;

  // 创建并发请求的Promise数组，每个团队发起一个请求
  const promises = teams.map((team) => {
    // 添加分页参数，使用较大的pageSize确保获取所有成员
    return getTeamMember(team.id, {
      pageNum: 1,
      pageSize: 100, // 设置较大的页面大小以获取所有成员11
    })
      .then((res) => {
        if (res && res.code === 200) {
          // 记录已加入的成员数量
          team.joinedCount = res.data?.student.length;
          return {
            teamId: team.id,
            count: res.data?.student.length,
          };
        }
        return {
          teamId: team.id,
          count: 0,
        };
      })
      .catch((err) => {
        console.error(`获取团队 ${team.id} 成员失败:`, err);
        return {
          teamId: team.id,
          count: 0,
        };
      });
  });

  // 使用Promise.all等待所有请求完成
  try {
    const results = await Promise.all(promises);
    // 更新状态
    results.forEach((result) => {
      teamMembersCount.value[result.teamId] = result.count;
    });
  } catch (error) {
    console.error("获取团队成员数量失败:", error);
  }
};

// 修改团队列表获取函数
const fetchTeamList = async () => {
  loading.value = true;
  // 构建查询参数
  const params = {
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    ...searchParams,
  };

  try {
    const res = await getTeamList(params);
    if (res && res.code === 200) {
      teamList.value = res.rows || [];
      console.log("队伍信息", teamList);

      pagination.total = res.total || 0;

      // 获取团队成员数量
      if (teamList.value.length > 0) {
        fetchTeamMembersCount(teamList.value);
      }
    } else {
      teamList.value = [];
      pagination.total = 0;
      message.warning(res?.msg || "暂无数据");
    }
  } catch (error) {
    console.error("获取团队列表错误:", error);
    message.error("获取团队列表失败，请稍后重试");
    teamList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handlePageChange = (page) => {
  pagination.current = page;
  fetchTeamList();
};

// 处理每页数量变化
const handleSizeChange = (current, size) => {
  pagination.current = 1;
  pagination.pageSize = size;
  fetchTeamList();
};


// 申请加入团队
const applyToTeam = (team) => {
  currentTeam.value = team;
  console.log("团队信息是", team);
  applyModalVisible.value = true;
  // 重置表单
  applicationForm.introduction = "";
  applicationForm.contact = "";
};

// 提交申请
const submitApplication = async () => {
  if (!applicationForm.introduction.trim()) {
    message.warning("请填写个人简介");
    return;
  }

  if (!applicationForm.contact.trim()) {
    message.warning("请填写联系方式");
    return;
  }

  submitLoading.value = true;

  const isUserTeacher = 0;
  const joinTeamData = {
    decisionRole: 0,
    isTeacher: isUserTeacher,
    race: currentTeam.value?.raceInfoVo?.id || 0, // 比赛
    reason: applicationForm.introduction, // 简介
    team: currentTeam.value?.id || 0, // 团队
    user: user.userInfo?.id || 0, // 用户id
  };
  console.log("joinTeamData:", joinTeamData);
  const res = await joinTeam(joinTeamData);
  console.log("res:", res);
  if (res && res.code === 200) {
    message.success(`已成功申请加入项目"${currentTeam.value.name}"`);
    applyModalVisible.value = false;
  }
  submitLoading.value = false;
};

// 查看团队详情
const currentTeamDetail = ref({});
const findOutVisible = ref(false);

const viewTeamDetail = async (team) => {
  const res = await getTeamDetail(team.id);
  currentTeamDetail.value = res.data;
  console.log("团队详情", currentTeamDetail.value);
  findOutVisible.value = true;
};

// 在页面加载时预先获取项目类型数据
onMounted(async () => {
  // 获取URL参数并设置筛选条件
  const { name, college, raceType } = route.query;
  if (name) searchParams.name = name;
  if (college) searchParams.college = college;
  if (raceType) searchParams.raceType = raceType;
  // 获取团队列表
  fetchTeamList();
  // 并行获取初始数据
  await Promise.all([fetchRaceTypes(), getCollegeList()]);
});
</script>

<style lang="less" scoped>
@card-bg: #fff;
@text-color: #333;
@text-secondary: #666;
@border-radius: 12px;
@box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
@primary-color: #667eea;
@primary-gradient: linear-gradient(90deg, #667eea, #764ba2);

.team-page-wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
}

.team-page-container {
  width: 100%;
  max-width: 1200px;
  padding: 20px;
  margin: 0 auto;
}

.team-search-section {
  background-color: @card-bg;
  border-radius: @border-radius;
  padding: 24px 24px 5px 24px;
  box-shadow: @box-shadow;
  margin-bottom: 24px;

  .search-header {
    text-align: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 8px;
      background: @primary-gradient;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .page-subtitle {
      color: @text-secondary;
      font-size: 16px;
    }
  }

  .search-filter-container {
    .filter-buttons {
      display: flex;
      gap: 12px;

      .ant-btn-primary {
        background: @primary-gradient;
        border: none;

        &:hover {
          background: linear-gradient(90deg, #764ba2, #667eea);
          box-shadow: 0 4px 6px rgba(118, 75, 162, 0.3);
        }
      }
    }
  }
}

.team-cards-container {
  .team-card {
    background-color: @card-bg;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
    }

    &.team-card-urgent {
      border-left: 4px solid #ff4d4f;
    }

    .urgent-tag {
      position: absolute;
      top: 10px;
      right: 0;
      background-color: #ff4d4f;
      color: white;
      padding: 3px 10px;
      font-size: 12px;
      border-radius: 12px 0 0 12px;
      z-index: 1;
    }

    .team-card-header {
      padding: 20px 20px 0;

      .team-card-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        h3 {
          font-size: 18px;
          font-weight: 600;
          margin: 0;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .team-college {
        color: @text-secondary;
        font-size: 14px;
        margin: 0 0 12px;
      }
    }

    .team-card-body {
      padding: 0 20px;
      flex: 1;

      .team-description {
        color: @text-color;
        margin-bottom: 16px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        font-size: 14px;
        min-height: 42px;
      }

      .team-members {
        margin-bottom: 16px;

        .members-title,
        .teacher-info {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
          font-size: 14px;
          color: @text-secondary;

          .anticon {
            color: @primary-color;
          }
        }
      }
    }

    .team-card-footer {
      padding: 16px 20px 20px;
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #f0f0f0;
      margin-top: auto;

      .join-button {
        background: @primary-gradient;
        border: none;

        &:hover {
          background: linear-gradient(90deg, #764ba2, #667eea);
          box-shadow: 0 4px 8px rgba(118, 75, 162, 0.3);
        }
      }
    }
  }

  .empty-container {
    padding: 40px 0;
    display: flex;
    justify-content: center;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  margin-bottom: 32px;
}

// 响应式调整
@media (max-width: 768px) {
  .team-page-container {
    padding: 16px;
  }

  .team-search-section {
    padding: 16px;

    .search-header {
      .page-title {
        font-size: 24px;
      }
    }
  }

  .team-cards-container {
    .team-card {
      .team-card-header {
        padding: 16px 16px 0;
      }

      .team-card-body {
        padding: 0 16px;
      }

      .team-card-footer {
        padding: 12px 16px 16px;
      }
    }
  }
}

.member-count {
  font-weight: 600;
  color: @primary-color;
}

// 添加加载中状态样式
.members-title {
  .loading-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    background-color: #ccc;
    border-radius: 50%;
    margin-right: 2px;
    animation: pulse 1.2s infinite;
  }
}

@keyframes pulse {
  0% {
    opacity: 0.3;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.3;
  }
}


.custom-modal {
  .modal-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .info-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 10px 0;
    border-bottom: 1px solid #e8e8e8;

    .info-item:last-child {
      border-bottom: none;
    }

    .label {
      font-weight: bold;
      margin-right: 16px;
      color: #333;
    }

    .value {
      flex: 1;
      color: #666;
    }
  }

}
</style>